//
//  PYCell.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/7.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit
import Kingfisher

//定义枚举 富文本链接类型
enum PYTextLinkType: Int {
    case Webpage
    case Picture
    case FullText
}


//标题富文本视图
class PYTextView: UITextView {
    //关闭高亮富文本的长按选中功能
    override func addGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) {
        if gestureRecognizer is  UILongPressGestureRecognizer {
            gestureRecognizer.isEnabled = false;
        }
        super.addGestureRecognizer(gestureRecognizer)
    }
    //打开或禁用复制，剪切，选择，全选等功能 UIMenuController
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        // 返回false为禁用，true为开启
        if action == #selector(copy(_ :)) || action == #selector(selectAll(_ :)) || action == #selector(select(_ :)) {
            return true
        }
        //        print("\(action)")
        return false
    }
}

//代理方法
@objc protocol PYTableViewCellDelegate : NSObjectProtocol {
    func tableViewCell(_ tableViewCell: PYCell, tapImageAction indexOfImages:NSInteger, indexPath: IndexPath)  //点击图片
    func tableViewCell(_ tableViewCell: PYCell, clickedLinks url:String,  characterRange: NSRange, linkType: SLTextLinkType.RawValue, indexPath: IndexPath)  //点击文本链接
}

class PYCell: SYBaseCell, SYPlayerDelegate {
    
    var model: NSRecordsModel!
    var player: SYPlayer?
    let fullScreenVC = SYFullScreenViewController()
    var imagesCount = 0
    var zanNum:Int = 0
    
    var imageViews: [AnimatedImageView] = []
    
    weak var delegate: PYTableViewCellDelegate?
    
    //当前cell索引
    var cellIndexPath: IndexPath?
    
    let head: UIImageView = {
        let v: UIImageView = UIImageView()
        v.clipsToBounds = true
        v.layer.cornerRadius = 20.autoWidth()
        return v
    }()
    
    let nameLb: UILabel = {
        let v:UILabel = UILabel()
        v.textColor = UIColor(hex: 0x526388)
        v.font = 16.autoBoldFontSize()
        
        return v
    }()
    
    let contentLb: UILabel = {
        let v:UILabel = UILabel()
        v.textColor = UIColor(hex: 0x1E1E1E)
        v.font = 17.autoFontSize()
        
        v.numberOfLines = 0
        return v
    }()
    
    let timeLb: UILabel = {
        let v:UILabel = UILabel()
        v.textColor = UIColor(hex: 0xACACAC)
        v.font = 12.autoFontSize()
        
        return v
    }()
    
    let play: UIImageView = {
        let v: UIImageView = UIImageView()
        v.image = UIImage(named: "play")
        v.isUserInteractionEnabled = true
        v.isHidden = true
        return v
    }()
    
    
    
    
    lazy var sixinBtn: VGBaseTitleImgView = {
        let v: VGBaseTitleImgView = VGBaseTitleImgView(frame: CGRect.zero)
        
        v.textLb.textColor = UIColor(hex: 0xACACAC)
        v.textLb.font = 12.autoFontSize()
        v.imageV.image = UIImage(named: "sixin")
        v.tapClosure = {[weak self] (index, isSelect) in
            if let weakSelf = self {
                
                if let vc = weakSelf.currentVC as? PYQListViewController {
                    vc.creatChatRoom(dId: weakSelf.model.id ?? "") { (res,success) in
                        if success {
                            DispatchQueue.main.async {
                                
                                let viewController = TSChatViewController.ts_initFromNib() as! TSChatViewController
                                let dict = ["":""]
                                let messageModel = TSMapper<MessageModel>().map(JSON: dict as [String : String])
                                messageModel?.chatId = res?.id
                                messageModel?.nickname = res?.appUserVoMap?.noMe?.trueName
                                viewController.messageModel = messageModel
                                vc.ts_pushAndHideTabbar(viewController)
                                
                            }
                        }
                    }
                }
            }
        }
        return v
    }()
    
    lazy var zanBtn: RYTitleImgView = {
        let v: RYTitleImgView = RYTitleImgView(frame: CGRect.zero)
        v.textLb.textColor = UIColor(hex: 0xACACAC)
        v.textLb.font = 12.autoFontSize()
        v.imageV.image = UIImage(named: "dianzan")
        v.normalName = "dianzan"
        v.selectName = "dianzan_select"
        v.isSelected = false
        v.tapClosure = {[weak self] (index, isSelect) in
            if let weakSelf = self {
                
                if let vc = weakSelf.currentVC as? PYQListViewController {
                    vc.dianzan(id: weakSelf.model.id ?? "") { (success) in
                        if success {
                            DispatchQueue.main.async {
                                
                                if !v.selected {
                                    weakSelf.zanNum -= 1
                                    v.textLb.text = "点赞 \(weakSelf.zanNum)"
                                    vc.sy_toast("取消点赞成功")
                                } else {
                                    weakSelf.zanNum += 1
                                    v.textLb.text = "点赞 \(weakSelf.zanNum)"
                                    weakSelf.creatToast()
                                }
                                
                            }
                        } 
                    }
                }
            }
        }
        return v
    }()
    
    
    
    func configureCell(urls: [String], model: NSRecordsModel, isVideo: Bool) {
        self.model = model
        
        
        if  model.hasDot > 0 {
            
            zanBtn.isSelected = true
        } else {
            
            zanBtn.isSelected = false
        }
        
        head.kf.setImage(with: URL(string: String(format: "%@%@", IMGIP, model.appUser?.headImg ?? "")))
        nameLb.text = model.appUser?.trueName
        contentLb.text = model.content
        timeLb.text = model.createDate
        sixinBtn.textLb.text = "私信 \(model.chatNum)"
        zanBtn.textLb.text = "点赞 \(model.dotNum)"
        zanNum = model.dotNum
        if urls.count == 0 {
            contentLb.snp.remakeConstraints { (make) in
                make.top.equalTo(head.snp.bottom).offset(10.0.autoWidth())
                make.left.equalToSuperview().offset(autoWidth(15.0))
                make.right.equalToSuperview().offset(autoWidth(-15.0))
                make.bottom.equalToSuperview().offset(-38.autoWidth())
            }
        } else {
            contentLb.snp.remakeConstraints { (make) in
                make.top.equalTo(head.snp.bottom).offset(10.0.autoWidth())
                make.left.equalToSuperview().offset(autoWidth(15.0))
                make.right.equalToSuperview().offset(autoWidth(-15.0))
                
            }
        }
        configureImageViews(urls: urls, isVideo: isVideo)
        
    }
    
    func configureImageViews(urls: [String], isVideo: Bool) {
        imagesCount = urls.count
        var width: Int = 0
        imageViews.forEach { (value) in
            // 清除之前约束
            value.snp.remakeConstraints { (make) in
                
            }
            play.snp.remakeConstraints { (make) in
                
            }
            value.isHidden = true
        }
        play.isHidden = true
        for (index, url) in urls.enumerated() {
            if index >= 6 {
                break
            }
            let imageView: AnimatedImageView = imageViews[index]
            imageView.kf.setImage(with: URL(string: url))
            imageView.isHidden = false
            if urls.count == 1 {
                imageView.addSubview(play)
                play.isHidden = !isVideo
                imageView.snp.makeConstraints { (make) in
                    make.top.equalTo(self.contentLb.snp.bottom).offset(10.autoWidth())
                    make.left.equalToSuperview().offset(15.autoWidth())
                    make.width.equalTo(SCREEN_WIDTH - 30.autoWidth())
                    make.height.equalTo(226.autoWidth())
                    make.bottom.equalToSuperview().offset(-38.autoWidth())
                }
                play.snp.makeConstraints { (make) in
                    make.center.equalToSuperview()
                }
            } else if urls.count == 2 {
                width = 168
                let left = (15 + index * (width + 10)).autoWidth()
                imageView.snp.makeConstraints { (make) in
                    make.top.equalTo(self.contentLb.snp.bottom).offset(10.autoWidth())
                    make.left.equalToSuperview().offset(left)
                    make.width.height.equalTo(width.autoWidth())
                    make.bottom.equalToSuperview().offset(-38.autoWidth())
                }
            } else if urls.count == 3 {
                width = 108
                let left = (15 + index * (width + 10)).autoWidth()
                imageView.snp.makeConstraints { (make) in
                    make.top.equalTo(self.contentLb.snp.bottom).offset(10.autoWidth())
                    make.left.equalToSuperview().offset(left)
                    make.width.height.equalTo(width.autoWidth())
                    make.bottom.equalToSuperview().offset(-38.autoWidth())
                }
            } else if urls.count > 3 {
                width = 108
                let top = (10 + (index/3) * (width + 10)).autoWidth()
                if index < 3 {
                    let left = (15 + index * (width + 10)).autoWidth()
                    imageView.snp.makeConstraints { (make) in
                        make.top.equalTo(self.contentLb.snp.bottom).offset(top)
                        make.left.equalToSuperview().offset(left)
                        make.width.height.equalTo(width.autoWidth())
                        make.bottom.equalToSuperview().offset(-38.autoWidth() - 10.autoWidth() - width.autoWidth())
                    }
                } else {
                    let left = (15 + (index - 3) * (width + 10)).autoWidth()
                    imageView.snp.makeConstraints { (make) in
                        make.top.equalTo(self.contentLb.snp.bottom).offset(top)
                        make.left.equalToSuperview().offset(left)
                        make.width.height.equalTo(width.autoWidth())
                        make.bottom.equalToSuperview().offset(-38.autoWidth())
                    }
                }
            }
        }
    }
    
    override func initViews() {
        
        creatImageViews()
        contentView.addSubview(nameLb)
        contentView.addSubview(head)
        contentView.addSubview(contentLb)
        contentView.addSubview(timeLb)
        contentView.addSubview(self.sixinBtn)
        contentView.addSubview(self.zanBtn)
        
        contentView.addSubview(lineView)
        
        
        
        head.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(17.0.autoWidth())
            make.left.equalToSuperview().offset(autoWidth(15.0))
            make.width.equalTo(40.0.autoWidth())
            make.height.equalTo(40.0.autoWidth())
        }
        nameLb.snp.makeConstraints { (make) in
            make.centerY.equalTo(head)
            make.left.equalTo(head.snp.right).offset(autoWidth(10.0))
            make.right.equalToSuperview().offset(autoWidth(-15.0))
            make.height.equalTo(16.0.autoWidth())
        }
        contentLb.snp.makeConstraints { (make) in
            make.top.equalTo(head.snp.bottom).offset(10.0.autoWidth())
            make.left.equalToSuperview().offset(autoWidth(15.0))
            make.right.equalToSuperview().offset(autoWidth(-15.0))
            
        }
        
        timeLb.snp.makeConstraints { (make) in
            make.bottom.equalTo(self).offset(-15.0.autoWidth())
            make.left.equalToSuperview().offset(autoWidth(15.0))
            make.height.equalTo(10.0.autoWidth())
            make.bottom.equalToSuperview().offset(-15.0.autoWidth())
        }
        sixinBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(timeLb)
            make.right.equalTo(zanBtn.snp.left).offset(-20.0.autoWidth())
            make.width.equalTo(65.0.autoWidth())
            make.height.equalTo(12.0.autoWidth())
        }
        
        zanBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(timeLb)
            make.right.equalTo(self).offset(-15.0.autoWidth())
            make.width.equalTo(65.0.autoWidth())
            make.height.equalTo(12.0.autoWidth())
        }
        
        
        lineView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(0.5.autoWidth())
            make.bottom.equalToSuperview()
        }
    }
    
    func creatImageViews() {
        
        for i in 0...5 {
            let imageView: AnimatedImageView = AnimatedImageView()
            imageView.clipsToBounds = true
            imageView.tag = i
            imageView.isUserInteractionEnabled = true
            contentView.addSubview(imageView)
            let tap: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(tapPicture(tap:)))
            imageView.addGestureRecognizer(tap)
            imageView.isHidden = true
            imageViews.append(imageView)
        }
    }
    
    func creatToast() {
        
        let toast: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 30))
        toast.backgroundColor = UIColor(hex: 0x367FF6, alpha: 0.7)
        toast.layer.cornerRadius = 5
        let lb: UILabel = UILabel()
        lb.text = "恭喜获得2积分"
        lb.textColor = .white
        lb.font = 15.autoFontSize()
        toast.addSubview(lb)
        lb.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.height.equalTo(13.autoWidth())
        }
            
        self.currentVC.view.showToast(toast, duration: 1.0, point:CGPoint(x: SCREEN_WIDTH/2, y: SCREEN_HEIGHT/2))
    }
    
    @objc func tapPicture(tap: UITapGestureRecognizer) {
        
        if imagesCount == 1 {
            setupVideoPlayer()
        } else {
            let animationView: AnimatedImageView = tap.view as! AnimatedImageView
            if (self.delegate?.responds(to: #selector(PYTableViewCellDelegate.tableViewCell(_:tapImageAction:indexPath:))))! {
                self.delegate?.tableViewCell(self, tapImageAction: animationView.tag, indexPath: self.cellIndexPath!)
            }
        }
    }
    
    // 播放视频
    func setupVideoPlayer() {
        
        let model = WMPlayerModel()
        model.videoURL = URL(string: IP + (self.model.resourceList?.first?.fileFullPath ?? ""))
        player = SYPlayer(model: model)
        self.addSubview(player!)// 播放音频需要addsubview，不用设置frame

        player!.play()
        player!.delegate = self
        
        /*
         NSURL *URL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"4k" ofType:@"mp4"]];
             playerModel.videoURL = [NSURL URLWithString:[URL absoluteString]];
         */
        
        fullScreenVC.syPlayer = player!
//        fullScreenVC.originalFrame = originalFrame
//        fullScreenVC.superView = self.videoContent
        
        fullScreenVC.shupingAction()
        self.currentVC.vg_present(fullScreenVC, animated: false)
        
    }
    
    func wmplayer(_ wmplayer: SYPlayer!, clickedFullScreenButton fullScreenBtn: UIButton!) {
        
        if fullScreenBtn.isSelected == true {
            fullScreenVC.fullScreenAction()
        } else {
            fullScreenVC.shupingAction()
        }
    }
    
    func wmplayer(_ wmplayer: SYPlayer!, clickedClose backBtn: UIButton!) {
        fullScreenVC.backAction()
        player!.pause()
        player = nil
    }
}



